package com.example.ssd4.util;

import javafx.geometry.Pos;
import javafx.scene.control.TextField;
import javafx.scene.control.cell.TextFieldTableCell;
import javafx.scene.input.MouseEvent;
import javafx.util.StringConverter;

public class EditableTextFieldTableCell<S, T> extends TextFieldTableCell<S, T> {
    private TextField textField;

    public EditableTextFieldTableCell(StringConverter<T> converter) {
        super(converter);
        setAlignment(Pos.CENTER);

        this.addEventFilter(MouseEvent.MOUSE_CLICKED, event -> {
            if (event.getClickCount() == 2 && !isEmpty()) {
                startEdit();
            }
        });
    }

    @Override
    public void startEdit() {
        super.startEdit();

        if (isEditing()) {
            textField = (TextField) getGraphic();
            textField.focusedProperty().addListener((obs, wasFocused, isNowFocused) -> {
                if (!isNowFocused) {
                    commitEdit(getConverter().fromString(textField.getText()));
                }
            });
        }
    }

    @Override
    public void commitEdit(T newValue) {
        if (isValidScore(newValue.toString().trim())) {
            newValue = (T)newValue.toString().trim();
            super.commitEdit(newValue);
        } else {
            cancelEdit(); // 取消编辑或者设置为原来的值
        }
    }

    @Override
    public void cancelEdit() {
        super.cancelEdit();
    }

    private boolean isValidScore(String text) {
        try {
            int score = Integer.parseInt(text.trim());
            return score >= 0 && score <= 100;
        } catch (NumberFormatException e) {
            return false;
        }
    }
}
